package com.yc.projectDemo;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.Paragraph;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.config.RequestConfig;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;

public class HttpClientExample {
    public static void main(String[] args) {
        String url = "http://www.nhc.gov.cn/wjw/xwdt/list.shtml";

        // 创建 Cookie 存储
        BasicCookieStore cookieStore = new BasicCookieStore();

        // 添加 Cookies
        BasicClientCookie cookie1 = new BasicClientCookie("sVoELocvxVW0S", "5u3VAGkQSkHvi.zC_G6OECpd0v7VX5vO5Wp3JU_N3vRj4Sk9TeDMY1SCUgUVT9XxGEei9fKJWmZXgpUkkFQa49G");
        BasicClientCookie cookie2 = new BasicClientCookie("insert_cookie", "91349450");
        BasicClientCookie cookie3 = new BasicClientCookie("arialoadData", "true");
//        BasicClientCookie cookie3 = new BasicClientCookie("ariawapChangeViewPort", "false");
        BasicClientCookie cookie4 = new BasicClientCookie("sVoELocvxVW0T", "5R5RP1DIb3PQqqqDY6tLcYGFgxdcs_cRz_doYIsaF2aI038rnTJPzMno3mAQ6BIhn0Op2PqwrANlziyokeauGGVsaGjxonf65ICMPTdwX6cuG3fVejp2oeTvfNMndjZ1wUUDCbuqeTvNz8rkd00A8jA4uwAUzUrV_YYGEIS6_MQ2hpC0.7ujy9mrOymw0jG6ZPQSukDFWyqN8xzqPoEUowJYfnX6UwcEsmkpeCzL9FziEbw0kabrlJjUvKEcB3CqkPzZdwmRfXNl.2GF0IOktOhlG1Pktig23Yi0i60bQ6msa");

        // 设置 Cookie 的作用域（必须正确）
        cookie1.setDomain("www.nhc.gov.cn");
        cookie1.setPath("/");
        cookie2.setDomain("www.nhc.gov.cn");
        cookie2.setPath("/");
        cookie3.setDomain("www.nhc.gov.cn");
        cookie3.setPath("/");
        cookie4.setDomain("www.nhc.gov.cn");
        cookie4.setPath("/");

        // 加入 CookieStore
        cookieStore.addCookie(cookie1);
        cookieStore.addCookie(cookie2);
        cookieStore.addCookie(cookie3);
        cookieStore.addCookie(cookie4);

        try {
			CloseableHttpClient httpClient = HttpClients.custom()
				.setDefaultCookieStore(cookieStore) // 设置 Cookie 存储
				.build();

            HttpGet request = new HttpGet(url);

            // 设置请求头
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
            request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            request.setHeader("Cache-Control", "max-age=0");
            request.setHeader("Proxy-Connection", "keep-alive");
            request.setHeader("Upgrade-Insecure-Requests", "1");
            request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");

            // 设置超时
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setSocketTimeout(5000)
                    .build();
            request.setConfig(config);

            // 发送请求
            CloseableHttpResponse response = httpClient.execute(request);
			String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			Document doc = Jsoup.parse(responseBody);
			System.out.println("文档：" + doc);
			createPdf(doc);


//			Elements newsItems = doc.select(".list > ul > li");
//			Elements newsList = doc.select(".list > ul > li");
//			for (Element item : newsItems) {
//				Element link = item.selectFirst("a"); // 新闻标题和链接
//				Element dateElement = item.selectFirst("span"); // 新闻日期
//
//				if (link != null && dateElement != null) {
//					String title = link.text();
//					String newsUrl = "http://www.nhc.gov.cn" + link.attr("href");
//					String date = dateElement.text();
//					System.out.println("标题: " + title);
//					System.out.println("URL: " + newsUrl);
//					System.out.println("日期: " + date);

					// 4. 输出到 PDF
//                        pdfDocument.add(new Paragraph("标题: " + title));
//                        pdfDocument.add(new Paragraph("URL: " + newsUrl));
//                        pdfDocument.add(new Paragraph("日期: " + date));
//                        pdfDocument.add(new Paragraph("--------------------------------------"));
//				}
//			}



        } catch (Exception e) {
            e.printStackTrace();
        }
    }


	public static void createPdf(org.jsoup.nodes.Document doc) {
		try {
			// 生成 PDF
			String pdfPath = "news.pdf";
			PdfWriter writer = new PdfWriter(new FileOutputStream(pdfPath));
			PdfDocument pdf = new PdfDocument(writer);
			com.itextpdf.layout.Document document = new com.itextpdf.layout.Document(pdf);

			// **加载中文字体**
			String fontPath = "/fonts/NotoSansCJKsc-Regular.otf";
			PdfFont font = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);


			// **设置文档字体**
			document.setFont(font);

			// 解析新闻列表
			Elements newsList = doc.select(".list > ul > li");
			for (Element item : newsList) {
				Element titleTag = item.selectFirst("a");
				Element dateTag = item.selectFirst("span");

				if (titleTag != null && dateTag != null) {
					String title = titleTag.text().trim();
					String url = titleTag.attr("href").trim();
					String date = dateTag.text().trim();
	//
	//				System.out.println(title);
	//				System.out.println(url);
	//				System.out.println(date);

					// 添加到 PDF
					document.add(new Paragraph("标题: " + title));
					document.add(new Paragraph("时间: " + date));
					document.add(new Paragraph("链接: http://www.nhc.gov.cn" + url));
					document.add(new Paragraph("\n"));
				}
			}

			// 关闭 PDF
			document.close();
			System.out.println("新闻数据已成功导出到: " + pdfPath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
